// pages/address/edit/edit.js
import { areaList } from '../../../utils/area-data/data.js';
// import { areaList } from '@vant/area-data'
Page({
  data:{
    areaList,
    showArea: false,
    selectedAddress: '',
    type: '',  // 标识是编辑,还是新增
    statusBarHeight: getApp().globalData.statusBarHeight, // 状态栏高度
    navHeight: getApp().globalData.navHeight,       // 导航栏总高度
    tabBarHeight: getApp().globalData.tabBarHeight,  // 底部高度
    form: {
      id: '',
      userName: '',
      telNumber: '',
      province: '',
      city: '',
      county: '',
      detail: '',
      isDefault: false
    },
    // regionText: ''
  },
  
  showAreaPicker() { this.setData({ showArea: true }) },

  hideAreaPicker() { this.setData({ showArea: false }) },
  
  // 返回上一页
  navigateBack() { wx.navigateBack() },

  onConfirm(e) {
    // 获取选中值（e.detail.values 为数组，包含省市区对象）
    const [province, city, county] = e.detail.values;
    this.setData({
      selectedAddress: province.name +' ' + city.name + ' ' + county.name,
      'form.province': province.name,
      'form.city': city.name,
      'form.county': county.name,
      showArea: false
    })
  },

  onLoad(options) {
    if (options.type === 'edit') {
      this.setData({type: 'edit'})
      this.loadEditData(options.index)       // 如果是编辑地址
    } else {
      this.setData({
        type:  options.type,
        form: { ...this.data.form, id: Date.now().toString(),
         }  // 如果是新增地址
      })
    }
  },
  
  // 加载编辑数据
  loadEditData(index) {
    const list = wx.getStorageSync('addressList') || []
    const data = list[index]
    this.setData({
      form: data,
      // regionText: `${data.province} ${data.city} ${data.county}`,
      selectedAddress: `${data.province} ${data.city} ${data.county}`
    })
  },

  // 切换默认地址
  // toggleDefault(e) {
  //   this.setData({
  //     'form.isDefault': e.detail.value
  //   })
  // },

  // 保存地址
  saveAddress(e) {
    const formData = e.detail.value
    const newAddress = {
      ...this.data.form,
      userName: formData.userName,
      telNumber: formData.telNumber,
      detail: formData.detail
    }
    if (!this.validateForm(newAddress)) return

    const list = wx.getStorageSync('addressList') || []
    if (this.data.type === 'edit') {
      const isExist = this.existsAddress(newAddress, list)  // 判断是否重复
      if(!isExist){
        const index = list.findIndex(item => item.id === this.data.form.id)
        list[index] = newAddress
        wx.setStorageSync('addressList', list)
        wx.navigateBack()
      }else{
        wx.showToast({ title: '跟已有地址重复', duration: 3000, icon: 'none' })
        // 3秒后执行回调
        setTimeout(() => {
          wx.navigateBack() // 示例：返回上一页
        }, 3000)  
      }

    } else {
      const isExist = this.existsAddress(newAddress, list)  // 判断是否重复
      if(!isExist){
        list.push(newAddress)
        wx.setStorageSync('addressList', list)
        wx.navigateBack()
      }else{
        wx.showToast({ title: '地址已经存在', duration: 2000, icon: 'none' })
        // 2秒后执行回调
        setTimeout(() => {
          wx.navigateBack() // 示例：返回上一页
        }, 2000)
      }
    }

  },

  // 判断新增地址是否会重复
  existsAddress(address, list) {
    const isExist = list.some(item => {
      // 提取比对字段（排除 id和isDefault）
      const { id: _, isDefault: __, ...restItem } = item;
      const { id, isDefault, ...restNewAddress } = address;
      // 比对字段数量和内容
      return Object.keys(restItem).length === Object.keys(restNewAddress).length 
        && Object.entries(restItem).every(([key, val]) => restNewAddress[key] === val);
    });
    return isExist
  },

  // 手机和固定电话验证
  validatePhoneNumber(number) {
    const mobileReg = /^1[3-9]\d{9}$/; // 手机号正则
    const landlineReg = /^(0\d{2}[- ]?\d{8}|0\d{3}[-,. ]?\d{7})$/; // 固话正则
    if (mobileReg.test(number) || landlineReg.test(number)) {
      return true;
    }
    wx.showToast({ 
      title: '格式错误：支持手机号或区号+电话',
      icon: 'none'
    });
    return false;
  },

  // 表单验证
  validateForm(data) {
    if (!data.userName) {
      wx.showToast({ title: '请输入收货人', icon: 'none' })
      return false
    }
    if (!this.validatePhoneNumber(data.telNumber)) return false;
    if (!data.province) {
      wx.showToast({ title: '请选择地区', icon: 'none' })
      return false
    }
    if (!data.detail) {
      wx.showToast({ title: '请输入详细地址', icon: 'none' })
      return false
    }
    return true
  }
})
